package com.catsic.practice.controller;

import com.catsic.practice.entity.*;
import com.catsic.practice.service.ThirdLeaveProcessService;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: zhangzf
 * @CreateTime: 2025-10-28  09:08
 * @Description: 控制器层
 */
@Slf4j
@RestController
@RequestMapping("/thirdLeaveProcess")
public class ThirdLeaveProcessController {

    @Autowired
    private ThirdLeaveProcessService thirdLeaveProcessService;

    /**
     * 创建请假申请
     */
    @PostMapping("/create")
    public Result createLeaveApplication(@Validated @RequestBody LeaveApplicationDTO leaveApplicationDTO){
        Map<String, Object> result = new HashMap<>();
        try {
            LeaveApplicationEntity application  =  new LeaveApplicationEntity();
            application.setApplyUser(leaveApplicationDTO.getApplyUser());
            application.setLeaveDays(leaveApplicationDTO.getLeaveDays());
            application.setLeaveReason(leaveApplicationDTO.getLeaveReason());
            application.setInstructor(leaveApplicationDTO.getInstructor());
            application.setHeadTeacher(leaveApplicationDTO.getHeadTeacher());
            application.setDirector(leaveApplicationDTO.getDirector());
            // 启动流程
            ProcessInstance processInstance = thirdLeaveProcessService.startLeaveProcess(application);
            result.put("processInstanceId", processInstance.getId());
            result.put("applicationId", application.getId());
            result.put("message", "请假申请创建成功");
            return Result.success(result);
        }catch (Exception e){
            log.error("创建请假申请失败", e);
            return Result.error("创建失败: " + e.getMessage());
        }
    }

    /**
     * 查询用户待办任务
     */
    @GetMapping("/tasks/{userId}")
    public Result getUserTasks(@PathVariable String userId){
        try{
            List<TaskDTO> tasks = thirdLeaveProcessService.getUserTasks(userId);
            return Result.success(tasks);
        }catch (Exception e){
            log.error("查询待办任务失败", e);
            return Result.error("查询待办任务失败: " + e.getMessage());
        }
    }

    /**
     * 学生提交申请到一级主管
     */
    @GetMapping("/submitToInstructor")
    public Result submitToInstructor(@RequestParam String taskId,@RequestParam String instructor){
        Map<String, Object> result = thirdLeaveProcessService.submitToInstructor(taskId, instructor);
        return Result.success(result);
    }

    /**
     * 查询候选用户待办任务
     */
    @GetMapping("/candidatesTasks/{userId}")
    public Result getCandidatesTasks(@PathVariable String userId){
        try{
            List<TaskDTO> tasks = thirdLeaveProcessService.getUserCandidates(userId);
            return Result.success(tasks);
        }catch (Exception e){
            log.error("查询待办任务失败", e);
            return Result.error("查询待办任务失败: " + e.getMessage());
        }
    }

    /**
     * 一级主管审批
     */
    @PostMapping("/first/approve")
    public Result firstApproval(@Validated@RequestBody ApprovalDTO approvalDTO){
        try{
            thirdLeaveProcessService.firstApproval(approvalDTO.getTaskId(),approvalDTO.getDecision(),approvalDTO.getComment(),
                    approvalDTO.getNextApprover());
            return Result.success("一级主管审批成功");
        }catch (Exception e){
            log.error("一级主管审批失败:{}", e.getMessage());
            return Result.error("审批失败: " + e.getMessage());
        }
    }

    /**
     * 二级主管审批
     */
    @PostMapping("/second/approve")
    public Result secondApproval(@Validated@RequestBody ApprovalDTO approvalDTO){
        try{
            thirdLeaveProcessService.secondApproval(approvalDTO.getTaskId(), approvalDTO.getDecision(), approvalDTO.getComment(),
                    approvalDTO.getNextApprover());
            return Result.success("二级主管审批成功");
        }catch (Exception e){
            log.error("二级主管审批失败", e);
            return Result.error("审批失败: " + e.getMessage());
        }
    }

    /**
     * 三级主管审批
     */
    @PostMapping("/third/approve")
    public Result thirdApproval(@Validated@RequestBody ApprovalDTO approvalDTO){
        try {
            thirdLeaveProcessService.thirdApproval(approvalDTO.getTaskId(), approvalDTO.getDecision(), approvalDTO.getComment());
            return Result.success("三级主管审批成功");
        }catch (Exception e){
            log.error("三级主管审批失败", e);
            return Result.error("审批失败: " + e.getMessage());
        }
    }

    /**
     * 获取审批历史
     */
    @GetMapping("/history/{processInstanceId}")
    public Result getApprovalHistory(@PathVariable String processInstanceId){
        try {
            List<ApprovalRecordEntity> history = thirdLeaveProcessService.getProcessHistory(processInstanceId);
            return Result.success(history);
        }catch (Exception e){
            log.error("获取审批历史失败", e);
            return Result.error("获取审批历史失败: " + e.getMessage());
        }
    }

    /**
     * 获取任务详情
     */
    @GetMapping("/task/{taskId}")
    public Result getApprovalTask(@PathVariable String taskId){
        try {
            TaskDTO task = thirdLeaveProcessService.getTaskById(taskId);
            return Result.success(task);
        }catch (Exception e){
            log.error("获取任务详情失败", e);
            return Result.error("获取任务详情失败: " + e.getMessage());
        }
    }
}
